package com.vitria.m3oui.rest.app.mgr;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import com.vitria.m3oui.security.XXTEA;

public class RestUtil {
	    private static final Log log_ = LogFactory.getLog(RestUtil.class);
	    
	    public static String M3OUI_PREFIX ="http://10.111.3.116:8080/m3oui"; //"http://localhost:8080/m3oui";
	    
	    public static String LOGIN_URL = M3OUI_PREFIX + "/rest/login";
	    public static String LOGOUT_URL = M3OUI_PREFIX + "/rest/logout";
	    public static String URL_PREFIX = M3OUI_PREFIX + "/rest";
	    
	    private static String TOKEN_NAME = "vttoken";	    
	    
	    protected static String login(String username, String password) throws Exception {
	        ClientResource resource = new ClientResource(LOGIN_URL);
	        try {
	        	String token_ = null;
	            Form form = new Form();
	            form.add("username", username);
	            form.add("password", XXTEA.encryptM3OData(password, ""));
	            Representation rep = resource.post(form.getWebRepresentation());
	            token_ = rep.getText();
	            System.out.println(token_);
	            return token_;
	        } catch(Exception e) {
	            log_.error(e.getMessage(), e);
	        }
	        return null;
	    }
	    
	    protected static void logout(String token) throws Exception {
	        ClientResource resource = new ClientResource(LOGOUT_URL);
	        attachToken(resource, token);
	        resource.get();
	    }
	    
	    /*protected void setHeader(ClientResource resource, String key, String value) {
	        HttpRequest request = (HttpRequest)resource.getRequest();
	        request.getHttpCall().getRequestHeaders().set(key, value);
	    }*/
	    
	    public static ClientResource createSecureClientResource(String url, String token) {
	        int pos = url.indexOf("?");
	        if(pos != -1) {
	            url += "&" + TOKEN_NAME + "=" + token;
	        } else {
	            url += "?" + TOKEN_NAME + "=" + token;
	        }
	        return new ClientResource(url);
	    }
	    
	    protected static void attachToken(ClientResource resource, String token) {
	        resource.getRequestAttributes().put(TOKEN_NAME, token);
	        // setHeader(resource, TOKEN_NAME, token_);
	    }
}
